package com.pactera.madp.cp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.cp.api.dto.BlacklistDTO;
import com.pactera.madp.cp.api.entity.WorkContactEntity;
import com.pactera.madp.cp.api.entity.WorkCorpBlacklistEntity;
import com.pactera.madp.cp.api.entity.WorkEmployeeEntity;
import com.pactera.madp.cp.api.vo.blacklist.BlacklistVo;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.mapper.WorkContactMapper;
import com.pactera.madp.cp.mapper.WorkCorpBlacklistMapper;
import com.pactera.madp.cp.mapper.WorkEmployeeMapper;
import com.pactera.madp.cp.service.IWorkContactService;
import com.pactera.madp.cp.service.IWorkCorpBlacklistService;
import lombok.Data;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Data
public class WorkCorpBlacklistServiceImpl extends ServiceImpl<WorkCorpBlacklistMapper, WorkCorpBlacklistEntity> implements IWorkCorpBlacklistService {

    @Autowired
    private WorkEmployeeMapper workEmployeeMapper;
    @Autowired
    private WorkContactMapper workContactMapper;
    @Autowired
    private IWorkContactService workContactService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R save(Integer corpId, BlacklistDTO dto) {

        WorkEmployeeEntity workEmployeeEntity = workEmployeeMapper.selectOne(Wrappers.<WorkEmployeeEntity>lambdaQuery().select(WorkEmployeeEntity::getName, WorkEmployeeEntity::getId)
                .eq(WorkEmployeeEntity::getId, dto.getEmployeeId()));
        WorkContactEntity workContactEntity = workContactMapper.selectOne(Wrappers.<WorkContactEntity>lambdaQuery().select(WorkContactEntity::getName,WorkContactEntity::getId)
                .eq(WorkContactEntity::getId, dto.getContactId()));
        QueryWrapper<WorkContactEntity> wrapper1 = new QueryWrapper<WorkContactEntity>();
        wrapper1.select("in_blacklist").eq("id", workContactEntity.getId()).eq("corp_id", CorpContextHolder.getCorpId());
        boolean inBlacklist = workContactService.getObj(wrapper1, o -> (Boolean) o);

        if (inBlacklist) return R.failed("该客户已在黑名单");

        WorkCorpBlacklistEntity workCorpBlacklistEntity = new WorkCorpBlacklistEntity();
        workCorpBlacklistEntity.setContactType(workContactEntity.getType());
        workCorpBlacklistEntity.setContactName(workContactEntity.getName());
        workCorpBlacklistEntity.setContactId(workContactEntity.getId());
        workCorpBlacklistEntity.setEmployeeName(workEmployeeEntity.getName());
        workCorpBlacklistEntity.setEmployeeId(workEmployeeEntity.getId());
        workCorpBlacklistEntity.setCorpId(corpId);
        workCorpBlacklistEntity.setReason(dto.getReason());
        workCorpBlacklistEntity.setCreateTime(LocalDateTime.now());
        boolean save = this.save(workCorpBlacklistEntity);
        if (save) {
            UpdateWrapper<WorkContactEntity> wrapper = new UpdateWrapper<WorkContactEntity>();
            wrapper.eq("id", workContactEntity.getId())
                    .set("in_blacklist", 1);
            workContactMapper.update(null,wrapper);
        }
        return save? R.ok("添加黑名单成功") : R.ok("添加黑名单失败");
    }

    @Override
    public IPage query(BlacklistDTO dto, Page page) {
        Integer corpId = CorpContextHolder.getCorpId();
        QueryWrapper<WorkContactEntity> contactWrapper = new QueryWrapper<>();
        contactWrapper.eq("is_blacklist", 1);
        List<Integer> contactIds = workContactMapper.selectAllIds(corpId);
        if (contactIds.size() == 0) contactIds.add(null);
        QueryWrapper<WorkCorpBlacklistEntity> wrapper = new QueryWrapper<>();

        if (dto.getContactName() != null && !dto.getContactName().trim().equals("")) {
            wrapper.like("contact_name", dto.getContactName());
        }
        if (dto.getEmployeeId() != null) {
            wrapper.eq("employee_id", dto.getEmployeeId());
        }
        if (dto.getContactType() != null) {
            wrapper.eq("contact_type", dto.getContactType());
        }
        wrapper.in("contact_id", contactIds);
        ArrayList<BlacklistVo> blacklistVos = new ArrayList<>();
        IPage page1 = this.page(page, wrapper);
        List list = (List<WorkCorpBlacklistEntity>) page1.getRecords();
        list.forEach(item -> {
            BlacklistVo vo = new BlacklistVo();
            BeanUtils.copyProperties(item, vo);
            blacklistVos.add(vo);
        });
//        blacklistVos.sort(comparing(BlacklistVo::getCreateTime));
        page1.setRecords(blacklistVos.stream().sorted(Comparator.comparing(BlacklistVo::getCreateTime).reversed()).collect(Collectors.toList()));
        return page1;
    }
    @Override
    public String getReason(Integer corpId, Integer contactId) {
        return this.baseMapper.selectLatestReason(corpId,contactId);
    }

}
